<template>
  <!-- 自定义的选择控件 -->
  <view class="custom-checkbox flex-wrap">
    <button
        :class="['wid-' + mr0Number, (index + 1) % mr0Number === 0 ? 'mr0' : '', modelValue.findIndex(cd => cd === item.value) > -1 ? 'primary' : '']"
        v-for="(item, index) in options"
        :key="index"
        plain="true"
        @click.stop="toggleChecked(item, index)">{{ item.name || item.text }}
    </button>
  </view>
</template>

<script setup>
import {ref, watch, computed} from 'vue';
import {parse, stringify} from '@/assets/js/util';

const props = defineProps({
  modelValue: { // 选中的value值
    type: Array,
    default: () => []
  },
  options: { // 选项(必须含有value, name 属性)
    type: Array,
    default: () => []
  },
  multiple: { // 是否多选
    type: Boolean,
    default: false
  },
  mr0Number: { // 表示第几个开始不需要右边距
    type: Number,
    default: 4
  },
  currentIndex: {
    type: Number,
    default: 0
  },
});

const emit = defineEmits(['update:change','change','update:modelValue','select']);

const toggleChecked = (item, i) => {
	console.log("item--------",item,i)
  let index = props.modelValue.findIndex(cd => cd === item.value), copy = parse(stringify(props.modelValue));
  if (index > -1) {
    props.multiple && copy.splice(index, 1);
  } else {
    props.multiple ? copy.push(item.value) : copy = [item.value];
  }
  // 返回选中的值 以及 对象
  let items = [];
  copy.forEach(element => {
    let idx = props.options.findIndex(it => it.value === element);
    if (idx > -1) {
      items.push(parse(stringify(props.options[idx])));
    }
  });
  emit('update:modelValue', copy, items, props.currentIndex, i);
  emit('change', copy, items, props.currentIndex, i);
  emit('select', item);
};
watch(() => props.options, (val) => {
  console.log(val)
},{immediate:true});
</script>

<style lang="scss" scoped>
@import '@/static/css/variable.scss';

.custom-checkbox {
  flex-wrap: wrap;

  :deep(uni-button) {
    &::before {
      display: none;
    }
    width: calc(25% - 7px);
    border-radius: 4px;
    border: 1px solid #EEEEEE !important;
    color: #666666;
    margin: 0 9px 9px 0;
    padding-left: 0 !important;
    padding-right: 0 !important;
    text-overflow: ellipsis;
    overflow: hidden;
    white-space: nowrap;
    &.wid-3 {
      width: calc(33.3% - 6px);
    }

    &.primary {
      color: var(--color);
      background: #fff;
      border-color: var(--color);
    }
  }
}
</style>